package com.onemileshop.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.onemileshop.controls.AdpLV_HomeOrderList;
import com.onemileshop.controls.AdpVP_Main;
import com.onemileshop.entiy.PubConst;
import com.onemileshop.entiy.Session;
import com.onemileshop.entiy.UrlParams;
import com.onemileshop.entiy.model.EMsgHead;
import com.onemileshop.entiy.model.EOrder;
import com.onemileshop.entiy.model.EOrderDetails;
import com.onemileshop.entiy.model.EPostData;
import com.onemileshop.entiy.model.EPostResult;
import com.onemileshop.net.NetGetOrderDetails;
import com.onemileshop.net.NetHomeTodayOrderList;
import com.onemileshop.service.RevCheckNewOrder;
import com.onemileshop.utils.UtiDialogsFactory;

import android.R.integer;
import android.R.string;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class UIMain extends Activity
{

   private int CURRENT_TAB = 0;
   private int TAB1 = 0;
   private int TAB2 = 1;

   // 第一页的控件=====================================
   private View tab1ToadyOrderView;// 布局文件
   private TextView txtShopName;
   private ListView listTodayOrders;
   private LinearLayout layHasOrder;
   private TextView txtOrderNum;
   private TextView txtNoOrder;
   private Button btnRefresh;

   // 第二页的控件=====================================
   private View tab2HistoryOrderView;

   // 第三页的控件=====================================

   // 本页控件========================================
   private LayoutInflater mInflater;
   private ViewPager mViewPager;
   private FrameLayout tab1Button;
   private FrameLayout tab2Button;
   private TextView txtTab1;
   private TextView txtTab2;

   /**
    * 初始化各个控件
    */
   private void InitControls()
   { // 本页控件========================================
	  mInflater = LayoutInflater.from(this);
	  tab1Button = (FrameLayout) findViewById(R.id.tab1_main);
	  tab2Button = (FrameLayout) findViewById(R.id.tab2_main);
	  txtTab1 = (TextView) findViewById(R.id.txtTab1_main);
	  txtTab2 = (TextView) findViewById(R.id.txtTab2_main);

	  // 第一页的控件=====================================
	  tab1ToadyOrderView = mInflater.inflate(R.layout.ui_home, null);
	  txtShopName = (TextView) tab1ToadyOrderView.findViewById(R.id.txtEmployeeName_home);
	  txtShopName.setText(Session.getInstance().getShopInfo().getShopsName());
	  listTodayOrders = (ListView) tab1ToadyOrderView.findViewById(R.id.lvTodayOrder_home);
	  layHasOrder = (LinearLayout) tab1ToadyOrderView.findViewById(R.id.layHasOrder_home);
	  txtNoOrder = (TextView) tab1ToadyOrderView.findViewById(R.id.txtNoOrder_home);
	  txtOrderNum = (TextView) tab1ToadyOrderView.findViewById(R.id.txtOrderNum_home);
	  btnRefresh = (Button) tab1ToadyOrderView.findViewById(R.id.btnRefresh_home);

	  // 第二页的控件=====================================
	  tab2HistoryOrderView = mInflater.inflate(R.layout.ui_history_order, null);

	  // 第三页的控件=====================================
   }

   private void InitControlsEvent()
   {
	  // 首页=============================================
	  tab1Button.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			SetTabSelected(TAB1);
		 }
	  });
	  tab2Button.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			SetTabSelected(TAB2);
		 }
	  });

	  // 第一页============================================
	  listTodayOrders.setOnItemClickListener(new AdapterView.OnItemClickListener()
	  {
		 @Override
		 public void onItemClick(AdapterView<?> parentView, View currentView, int position, long arg3)
		 {
			LoadOrderDetail((EOrder) (listTodayOrders.getAdapter().getItem(position)));
		 }
	  });
	  btnRefresh.setOnClickListener(new View.OnClickListener()
	  {
		 @Override
		 public void onClick(View v)
		 {
			LoadTodayOrders();
		 }
	  });

	  // 第二页============================================

	  // 第三页============================================
   }

   private void InitViewPage()
   {
	  List<View> list = new ArrayList<View>();
	  list.add(tab1ToadyOrderView);
	  list.add(tab2HistoryOrderView);

	  mViewPager = (ViewPager) findViewById(R.id.vp_main);
	  AdpVP_Main adpMain = new AdpVP_Main(list);
	  mViewPager.setAdapter(adpMain);
	  mViewPager.setCurrentItem(TAB1);
	  mViewPager.setOnPageChangeListener(new OnPageChangeListener()
	  {
		 @Override
		 public void onPageSelected(int index)
		 {
			SetTabSelected(index);
		 }

		 @Override
		 public void onPageScrolled(int arg0, float arg1, int arg2)
		 {
		 }

		 @Override
		 public void onPageScrollStateChanged(int arg0)
		 {
		 }
	  });
   }

   /**
    * 根据有没有订单显示界面
    * 
    * @param hasOrder
    *           是否有订单
    */
   private void SetHomeView(boolean hasOrder)
   {
	  if (hasOrder)
	  {
		 layHasOrder.setVisibility(View.VISIBLE);
		 txtNoOrder.setVisibility(View.GONE);
		 listTodayOrders.setVisibility(View.VISIBLE);
	  }
	  else
	  {
		 layHasOrder.setVisibility(View.GONE);
		 txtNoOrder.setVisibility(View.VISIBLE);
		 listTodayOrders.setVisibility(View.GONE);
	  }
   }

   // private void SetOrderListTab1(List<ModOrder> list)
   // {
   // AdpLV_HomeOrders adapter = new AdpLV_HomeOrders(list, UIMain.this);
   // listTodayOrders.setAdapter(adapter);
   // }

   @SuppressWarnings("unchecked")
   private void LoadTodayOrders()
   {
	  try
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIMain.this, "获取数据中。。。");

		 NetHomeTodayOrderList task = new NetHomeTodayOrderList(new EMsgHead(UrlParams.Shop_GetTodayOrderList.APICode), new NetHomeTodayOrderList.ITaskCallBack()
		 {
			@Override
			public void DoWhenComplete(EPostResult result)
			{
			   try
			   {
				  if (result == null)
				  {

				  }
				  else if (result.getRspCode().equals("00000000"))
				  {
					 @SuppressWarnings("unchecked")
					 AdpLV_HomeOrderList adp = new AdpLV_HomeOrderList((ArrayList<EOrder>) result.getResult(), UIMain.this);
					 listTodayOrders.setAdapter(adp);

					 SharedPreferences.Editor editor = getSharedPreferences(PubConst.Setting.Setting, Activity.MODE_PRIVATE).edit();
					 editor.putInt(UrlParams.Shop_CheckNewOrder.OrderNumber, ((EOrder) listTodayOrders.getAdapter().getItem(0)).getOrderNumber());
					 editor.commit();

					 txtOrderNum.setText(String.valueOf(listTodayOrders.getAdapter().getCount()));
				  }
				  else
				  {
					 UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIMain.this, "提示", result.getRspMsg());
					 txtOrderNum.setText(String.valueOf(0));
				  }

			   }
			   catch (Exception e)
			   {
				  Log.e("ERROR", "LoadTodayOrders()-DoWorkWhenComplete()", e);
			   }
			   finally
			   {
				  UtiDialogsFactory.getInstance().DismissLoadingDialog();
				  SetCheckNewOrderListener();
			   }
			}
		 });
		 ArrayList<EPostData> list = new ArrayList<EPostData>();
		 list.add(new EPostData(UrlParams.Shop_GetTodayOrderList.ShopId, Session.getInstance().getShopInfo().getShopsId()));
		 task.execute(list);
	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIMain_LoadTodayOrders() ", e);
		 }
	  }
   }

   @SuppressWarnings("unchecked")
   private void LoadOrderDetail(final EOrder order)
   {
	  try
	  {
		 UtiDialogsFactory.getInstance().ShowLoadingDialogNoTitle(UIMain.this, "获取订单信息中，请稍候。。。");
		 NetGetOrderDetails task = new NetGetOrderDetails(new EMsgHead(UrlParams.Shop_GetOrderDetails.APICode), new NetGetOrderDetails.ITaskCallBack()
		 {
			@Override
			public void DoWhenComplete(EPostResult result)
			{
			   try
			   {
				  if (result == null)
				  {

				  }
				  else if (result.getRspCode().equals("00000000"))
				  {
					 Intent intent = new Intent();
					 intent.setClass(UIMain.this, UIOrderDetails.class);
					 intent.putParcelableArrayListExtra("OrderDetails", (ArrayList<EOrderDetails>) result.getResult());
					 intent.putExtra("Order", order);
					 startActivityForResult(intent, PubConst.ActivityCode.HOME);
				  }
				  else
				  {
					 UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIMain.this, "提示", result.getRspMsg());
				  }

			   }
			   catch (Exception e)
			   {
				  Log.e("ERROR", "LoadTodayOrders()-DoWorkWhenComplete()", e);
				  UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIMain.this, "提示", "没有找到此订单或网络故障");
			   }
			   finally
			   {
				  UtiDialogsFactory.getInstance().DismissLoadingDialog();
			   }
			}
		 });
		 ArrayList<EPostData> list = new ArrayList<EPostData>();
		 list.add(new EPostData(UrlParams.Shop_GetOrderDetails.OrderId, order.getOrderId()));
		 task.execute(list);

	  }
	  catch (Exception e)
	  {
		 if (Session.getInstance().IsDEBUG())
		 {
			Log.e("ERROR", "UIMain_LoadOrderDetail(orderId) ", e);
		 }
	  }
   }

   private void SetTabSelected(int index)
   {
	  switch (index)
	  {
		 case 0:
			tab1Button.setBackgroundResource(R.color.White);
			tab2Button.setBackgroundResource(R.color.Brown);
			mViewPager.setCurrentItem(index);
			break;

		 case 1:
			tab1Button.setBackgroundResource(R.color.Brown);
			tab2Button.setBackgroundResource(R.color.White);
			mViewPager.setCurrentItem(index);
			break;
	  }
   }

   private void SetCheckNewOrderListener()
   {
	  Intent intent = new Intent(this, RevCheckNewOrder.class);
	  intent.setAction(PubConst.Action.CheckNewOrder);
	  intent.putExtra(UrlParams.Shop_CheckNewOrder.ShopId, Session.getInstance().getShopInfo().getShopsId());
	  PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
	  AlarmManager am2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
	  am2.cancel(pIntent);
	  am2.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PubConst.UPLOAD_TIME, pIntent);
   }

   private void CancelCheckNewOrderListener()
   {
	  Intent intent = new Intent(this, RevCheckNewOrder.class);
	  intent.setAction(PubConst.Action.CheckNewOrder);
	  intent.putExtra(UrlParams.Shop_CheckNewOrder.ShopId, Session.getInstance().getShopInfo().getShopsId());
	  PendingIntent pIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
	  AlarmManager am2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
	  am2.cancel(pIntent);
   }

   private void CancelNotification()
   {
	  NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
	  Notification notification = new Notification(R.drawable.app_icon, "又有新的订单了！", System.currentTimeMillis());
	  notification.setLatestEventInfo(UIMain.this, "新订单消息", "点击查看新订单消息", PendingIntent.getActivity(UIMain.this, 0, new Intent(UIMain.this, UIMain.class), 1));
	  notification.flags |= Notification.FLAG_AUTO_CANCEL; // 点击后消失
	  notification.defaults |= Notification.DEFAULT_SOUND; // 设置声音
//	  manager.cancel(id) // 触发事件时，会不会重复显示多个消息
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  super.onCreate(savedInstanceState);
	  setContentView(R.layout.ui_main);
	  if(!Session.getInstance().isLogin())
	  {
		 Intent intent=new Intent(UIMain.this, UILogin.class);
		 startActivity(intent);
		 finish();
	  }
	  InitControls();
	  InitControlsEvent();
	  InitViewPage();
	  LoadTodayOrders();

   }

   @Override
   protected void onResume()
   {
	  // String currentName=getSharedPreferences(PubConst.Key.Setting,
	  // Activity.MODE_PRIVATE).getString(PubConst.Key.CURRENT_USERNAME,"");
	  // if(currentName.equals(""))
	  // {
	  // Intent intent=new Intent();
	  // intent.setClass(UIMain.this, UILogin.class);
	  // startActivity(intent);
	  // finish();
	  // }
	  super.onResume();
   }

   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent returnIntent)
   {
	  switch (requestCode)
	  {
		 case PubConst.ActivityCode.HOME:
			if (resultCode == RESULT_OK)
			{
			   // mOrder = (ModOrder)
			   // returnIntent.getSerializableExtra("order");
			   UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIMain.this, "提示", "确认成功!");
			}
			else
			{

			}
			break;

		 case PubConst.ActivityCode.ORDER_DETAILS:
			if (resultCode == RESULT_OK)
			{
			   // mOrder = (ModOrder)
			   // returnIntent.getSerializableExtra("order");
			   UtiDialogsFactory.getInstance().ShowOKAlertDialog(UIMain.this, "提示", "确认成功!");
			}
			else
			{

			}
			break;
	  }
   }

   @Override
   protected void onDestroy()
   {
	  CancelCheckNewOrderListener();
	  super.onDestroy();
   }

   // 退出提示框
   private void FinishDialog()
   {
	  DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
	  {
		 @Override
		 public void onClick(DialogInterface dialog, int which)
		 {
			dialog.dismiss();	
			CancelCheckNewOrderListener();
			Session.getInstance().Logout();		
			finish();
			android.os.Process.killProcess(android.os.Process.myPid());

		 }
	  };
	  UtiDialogsFactory.getInstance().ShowOKCancelAlertDialog(UIMain.this, "提示", "您打算退出程序吗？", listener);
   }

   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
   {
	  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)
	  {
		 FinishDialog();
	  }
	  return true;
   }
}
